<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>元素拖拽</title>
    <style>
      #box1 {
        height: 100px;
        width: 100px;
        background-color: red;
        position: absolute;
      }
      #box2 {
        height: 100px;
        width: 100px;
        background-color: yellow;
        position: absolute;
        left: 200px;
        top: 200px;
      }
    </style>
  </head>
  <body>
    我是一段文字
    <div id="box1"></div>
    <div id="box2"></div>

    <script>
      /*
      拖拽的流程：
      1. 当鼠标在被拖拽元素上摁下时开始拖拽 onmousedown
      2. 当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
      3. 当鼠标松开时，被拖拽元素固定在当前位置 onmouseup
       */

      window.onload = function () {
        var box1 = document.getElementById("box1");
        var box2 = document.getElementById("box2");

        drag(box1);
        drag(box2);
      };

      function drag(element) {
        element.onmousedown = function (event) {
          var ol = event.clientX - element.offsetLeft;
          var ot = event.clientY - element.offsetTop;

          document.onmousemove = function (event) {
            event = event || window.event;
            var left = event.clientX - ol;
            var top = event.clientY - ot;

            element.style.left = left + "px";
            element.style.top = top + "px";

            document.onmouseup = function () {
              document.onmousemove = null;
              document.onmouseup = null;
            };
          };

          return false;
        };
      }
    </script>
  </body>
</html>
